package com.fc.advbox.controller.admin;

import com.fc.advbox.common.ResponseJson;
import com.fc.advbox.dto.admin.UserRegRequest;
import com.fc.advbox.dto.user.AdvUserReqDto;
import com.fc.advbox.dto.user.UserPointDto;
import com.fc.advbox.entity.AdvUserEntity;
import com.fc.advbox.entity.SmsHistoryEntity;
import com.fc.advbox.entity.UserPointEntity;
import com.fc.advbox.service.ISmsHistoryService;
import com.fc.advbox.service.IUserPointService;
import com.fc.advbox.service.IUserService;
import com.fc.advbox.utils.*;
import com.fc.advbox.utils.annotation.IgnoreAuth;
import com.fc.advbox.utils.annotation.SysLog;
import com.fc.advbox.utils.validator.Assert;
import com.fc.advbox.utils.validator.ValidatorUtils;
import com.fc.advbox.utils.validator.group.AddGroup;
import com.fc.advbox.utils.validator.group.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author Rocky
 */
@RestController
@RequestMapping("/api/admin/user")
@Api(value="管理端-维护用户相关的API", tags={"用户管理接口"})
public class UserAdminController extends BaseController {
	private final IUserService userService;

	private final ISmsHistoryService iSmsHistoryService;


    @Autowired
    public UserAdminController(IUserService userService, ISmsHistoryService smsHistoryService) {
        this.userService = userService;
        this.iSmsHistoryService = smsHistoryService;
    }

    /**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:user")
	public ResponseJson list(@RequestParam Map<String, Object> params){
		//只有超级管理员，才能查看所有管理员列表
		if(getUserId() != Constant.SUPER_ADMIN){
			params.put("createUserId", getUserId());
		}
		
		//查询列表数据
		Query query = new Query(params);
		List<AdvUserEntity> userList = userService.queryList(query);
		int total = userService.queryTotal(query);
		
		PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
		
		return ResponseJson.success(pageUtil);
	}

	
	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("admin:user")
	public ResponseJson info(@PathVariable("userId") Long userId){
		AdvUserEntity user = userService.queryObject(userId);
		
		//获取用户所属的角色列表
//		List<Long> roleIdList = ISysUserRoleService.queryRoleIdList(userId);
//		user.setRoleIdList(roleIdList);
		return ResponseJson.success(user);
	}

	/**
	 * 注册
	 */
	@IgnoreAuth
	@PostMapping("register")
	@ApiOperation(value = "注册")
	public ResponseJson registerUser(@RequestBody UserRegRequest reg){
		ResponseJson responseJson = new ResponseJson();
		Assert.isBlank(reg.getPhone(), "手机号不能为空");
		Assert.isBlank(reg.getPasswd(), "密码不能为空");
		//TODO: verify verifyCode

		SmsHistoryEntity smsHistoryEntity = iSmsHistoryService.queryByMobileAndCode(reg.getPhone(), reg.getVerifyCode());
		if (null == smsHistoryEntity)
		{
			return ResponseJson.error(200, "验证码不正确");
		}
		if(userService.queryByMobile(reg.getPhone()) != null){
			responseJson.setSuccess(false);
			responseJson.setMsg("该手机号已注册");
			return responseJson;
		}

		userService.save(reg.getPhone(), reg.getPasswd());
		responseJson.setSuccess(true);
		responseJson.setMsg("");
		return responseJson;
	}


	/**
	 * 保存用户
	 */
	@ApiOperation(value = "POST User Save 创建(创建)用户",
			notes = " REST 方式登录。" +
					"使用方式: <ul>" +
					"<li><i>用户名</i></li>" +
					"<li><i>密码</i></li>" +
					"<li><i>TYPE (用户类型)：1:管理公司,2: 代理商,3:渠道商,4:租户广告商,5:投资人,</i></li>" +
					"<li><i>PHONE ：电话号码</i></li>" +
					"<li><i>NAME ： 用户名</i></li>" +
					"<li><i>REAL_NAME ： 实名，投资人用户选填</i></li>" +
					"<li><i>EMAIL：邮箱</i></li>" +
					"<li><i>IDCARD：身份证，使用投资人用户选填</i></li>" +
					"<li><i>AVATAR : 头像地址 可不填</i></li>" +
					"<li><i>DEVICE_UUID : 设备UUID 可不填</i></li>" +
					"<li><i>OPEN_ID : 可不填</i></li>" +
					"<li><i>ORG_ID : 机构用户选填</i></li>" +
					"</ul>",
			response = ResponseJson.class,
			httpMethod = "POST",
			consumes = "application/json",
			produces = "application/json",
			code = 200
	)
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("admin:user")
	public ResponseJson save(@RequestBody AdvUserReqDto user){
		ValidatorUtils.validateEntity(user, AddGroup.class);
		userService.save(user);
		return ResponseJson.success();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PutMapping("/update")
	@RequiresPermissions("admin:user:update")
	public ResponseJson update(@RequestBody AdvUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		userService.update(user);
		
		return ResponseJson.success();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@DeleteMapping("/delete")
	@RequiresPermissions("admin:user:delete")
	public ResponseJson delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return ResponseJson.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return ResponseJson.error("当前用户不能删除");
		}
		
		userService.deleteBatch(userIds);
		
		return ResponseJson.success();
	}


}
